package com.mmall.example.concurrent;

import com.mmall.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.*;

/**
 * ConcurrentSkipListSet 并发容器 -> 线程安全的
 * Created by megan on 2018/4/2.
 */
@Slf4j
@ThreadSafe
public class ConcurrentSkipListSetExample {

    /** 请求数 **/
    public static int clientTotal = 5000;

    /** 同时并发执行线程数 **/
    public static int threadTotal = 200;

    private static Set<Integer> list = new ConcurrentSkipListSet<>();

    public static void main(String[] args) throws  Exception{
        //定义一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 信号量，闭锁
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        // 模拟并发请求
        for(int i = 0; i < clientTotal; i ++){
            final int count = i ;
            executorService.execute(() -> {
                try {
                    // 请求一个信号，如果信号量小于clientTotal，则阻塞
                    semaphore.acquire();
                    concurrentSkipListSet(count);
                    // 释放一个信号
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception",e);
                }
                countDownLatch.countDown();
            });
        }
        // 阻塞直到countDown 的次数为threadTotal
        countDownLatch.await();
        // 关闭线程池
        executorService.shutdown();
        log.info("size:{}",list.size());
    }

    /** 每次执行的时候执行 parse **/
    private static void concurrentSkipListSet(int count){
        list.add(count);
    }

}
